import React, {useEffect, useState} from 'react';
import classes from './index.module.scss'
import {Avatar, Button, Card, Empty, Image, List, message, Modal, Skeleton} from "antd";
import {useNavigate} from "react-router-dom";
import {reqDeleteMyCourseOrder, reqGetMyCourseList} from "../../../../api/frontDesk/frontDeskApi";
import {useDispatch, useSelector} from "react-redux";

const tabListNoTitle = [
    {
        key: 'my_course',
        tab: '我的课程',
    },
    {
        key: 'buy_record',
        tab: '购买记录',
    },
];


const MyCourse = () => {


    const [activeTabKey1, setActiveTabKey1] = useState('my_course');
    const [index, setIndex] = useState(0)
    const nav = useNavigate()

    const [myCourseList, setMyCourseList] = useState([])
    const [myBuyCourseList, setMyBuyCourseList] = useState([])

    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [deleteId, setDeleteId] = useState(null);
    const [deleteMyId, setDeleteMyId] = useState(null);

    const {userAllInfo} = useSelector(state => state.persistedReducer.user)


    useEffect(() => {
        //获取数据
        getMyCourseList()
    }, [])
    const getMyCourseList = async () => {
        const result = await reqGetMyCourseList(userAllInfo.id)
        console.log(result.data)
        setMyCourseList(() => {
            // 使用reduce去重
            // const data = result.data.reduce((acc, item) => {
            //     if (!acc.some(i => i.id === item.id)) {
            //         acc.push(item);
            //     }
            //     return acc;
            // }, []);
            const data = new Map()
            result.data.forEach(item => {
                data.set(item.id, item);
            });
            const newData = Array.from(data.values())
            if (data.size > 0) {
                return newData
            } else {
                return [];
            }
        })
        setMyBuyCourseList(result.data)
    }


    const setColor = () => {
        setIndex(0)
    }

    //页签切换
    const onTab1Change = (key) => {
        setActiveTabKey1(key)
    };

    const deleteCourse = (id) => {
        setDeleteId(id)
        setOpen(true)
    }

    const deleteMyCourse = (id) => {
        setDeleteMyId(id)
        setOpen(true);
    }

    const deleteCourseOk = () => {
        if (deleteMyId) {
            setConfirmLoading(true);
            setTimeout(() => {
                const newList = myCourseList.filter((item) => item.order_id !== deleteMyId)
                setMyCourseList(newList)
                setOpen(false);
                setConfirmLoading(false);
                message.success('删除成功!')
            }, 1000);
        } else {
            setConfirmLoading(true);
            setTimeout(async () => {
                const result = await reqDeleteMyCourseOrder({order_id: deleteId})
                if (result.status === 0) {
                    setOpen(false);
                    setConfirmLoading(false);
                    message.success('删除成功!')
                    getMyCourseList()
                } else {
                    message.error('删除失败!')
                }
            }, 1000);
        }

    };
    const deleteCourseCancel = () => {
        setConfirmLoading(false)
        setOpen(false);
    };


    //内容
    const contentListNoTitle = {
        my_course: <div>
            <div className={classes.CourseBtn}>
                <Button onClick={setColor}
                        style={{padding: 0, color: (index === 0) ? "#1677ff" : "unset"}}
                        type="link"
                        size="large">全部课程</Button>
                {
                    myCourseList.length > 0 &&
                    <List
                        itemLayout="horizontal"
                        dataSource={myCourseList}
                        renderItem={(item) => (
                            <List.Item className={classes.ListItem}
                                       actions={[<a onClick={() => deleteMyCourse(item.order_id)}>删除</a>]}
                            >
                                <Skeleton avatar title={false} loading={item.loading} active>
                                    <List.Item.Meta
                                        style={{display: 'flex', alignItems: 'center'}}
                                        avatar={<Image width={80} src={item.cover}/>}
                                        title={<a href="https://ant.design">{item.author_name}</a>}
                                        description={item.describe}
                                    />
                                </Skeleton>
                            </List.Item>
                        )}
                    />
                }
                {
                    myCourseList.length === 0 &&
                    <Empty
                        description="暂无数据"
                        className={classes.Empty}>
                        <Button onClick={() => nav('/course')}>回到课程首页</Button>
                    </Empty>
                }
            </div>
        </div>,
        buy_record: <div style={{fontSize: 16}}>
            {
                myBuyCourseList.length > 0 &&
                <List
                    itemLayout="horizontal"
                    dataSource={myBuyCourseList}
                    renderItem={(item) => (
                        <List.Item
                            className={classes.ListItem}
                            actions={[<a onClick={() => deleteCourse(item.order_id)}>删除</a>]}
                        >
                            <Skeleton avatar title={false} loading={item.loading} active>
                                <List.Item.Meta
                                    style={{display: 'flex', alignItems: 'center'}}
                                    avatar={<Image width={80} src={item.cover}/>}
                                    title={<a href="https://ant.design">{item.author_name}</a>}
                                    description={item.describe}
                                />
                                <span style={{color: 'red', fontSize: 20}}>￥{item.now_price}</span>
                            </Skeleton>
                        </List.Item>
                    )}
                />
            }
            {
                myBuyCourseList.length === 0 &&
                <Empty
                    description="暂无数据"
                    className={classes.Empty}>
                    <Button onClick={() => nav('/course')}>回到课程首页</Button>
                </Empty>
            }
        </div>,
    };


    return (
        <div className={classes.MyCourse}>
            <Card
                className={classes.MyCourseCard}
                tabList={tabListNoTitle}
                activeTabKey={activeTabKey1}
                onTabChange={(key) => {
                    onTab1Change(key)
                }}
            >
                {contentListNoTitle[activeTabKey1]}

            </Card>
            <>
                <Modal
                    centered
                    title="确认要删除订单记录吗?"
                    open={open}
                    onOk={deleteCourseOk}
                    confirmLoading={confirmLoading}
                    onCancel={deleteCourseCancel}
                    okText={"确认"}
                    cancelText={"取消"}
                >
                </Modal>
            </>
        </div>
    );
};

export default MyCourse;